<template>
  <div class="login">
    <!-- 背景装饰元素 -->
    <div class="background-decorations">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
      <div class="decoration-wave"></div>
    </div>
    
    <!-- 登录表单容器 -->
    <div class="login-container">
      <!-- 品牌区域 -->
      <div class="brand-section">
        <div class="brand-logo">
          <svg-icon icon-class="chart" class="logo-icon" />
        </div>
        <h1 class="system-title">电商平台评论分析系统</h1>
        <p class="system-description">智能分析 · 数据驱动 · 精准洞察</p>
      </div>
      
      <!-- 登录表单 -->
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="form-title">用户登录</h3>
        
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="el-icon-user"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="请输入密码"
            size="large"
            prefix-icon="el-icon-lock"
            @keyup.enter.native="handleLogin"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="code" v-if="captchaEnabled">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              placeholder="请输入验证码"
              size="large"
              prefix-icon="el-icon-key"
              @keyup.enter.native="handleLogin"
            >
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" alt="验证码"/>
            </div>
          </div>
        </el-form-item>
        
        <div class="form-options">
          <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
          <a href="#" class="forgot-password">忘记密码？</a>
        </div>
        
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="large"
            type="primary"
            class="login-button"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
        
        <!-- 系统特色说明 -->
        <div class="feature-section">
          <div class="feature-item">
            <i class="el-icon-data-analysis feature-icon"></i>
            <span>智能情感分析</span>
          </div>
          <div class="feature-item">
            <i class="el-icon-trend-charts feature-icon"></i>
            <span>实时数据监控</span>
          </div>
          <div class="feature-item">
            <i class="el-icon-warning-outline feature-icon"></i>
            <span>异常评论预警</span>
          </div>
        </div>
      </el-form>
    </div>
    
    <!-- 底部信息 -->
    <div class="login-footer">
      <span>© 2025 电商平台评论分析系统 | 技术支持：数据分析团队</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      currentCode: "", // 存储当前生成的验证码用于验证
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关 - 始终启用
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // 确保验证码在组件创建时就生成
    this.captchaEnabled = true
    this.getCode()
    this.getCookie()
  },
  methods: {
    // 生成随机验证码
    generateRandomCode() {
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
      let code = ''
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      return code
    },
    
    // 创建SVG验证码
    createSvgCaptcha() {
      const code = this.generateRandomCode()
      this.currentCode = code // 存储当前验证码用于验证
      
      // 创建干扰线和点的随机位置
      const lines = []
      const dots = []
      for (let i = 0; i < 4; i++) {
        lines.push({
          x1: Math.random() * 120,
          y1: Math.random() * 40,
          x2: Math.random() * 120,
          y2: Math.random() * 40,
          stroke: `rgb(${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)})`
        })
      }
      for (let i = 0; i < 30; i++) {
        dots.push({
          cx: Math.random() * 120,
          cy: Math.random() * 40,
          r: Math.random() * 1 + 0.5,
          fill: `rgb(${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)})`
        })
      }
      
      // 生成SVG字符串
      let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="40" viewBox="0 0 120 40">`
      svg += `<rect width="120" height="40" fill="#f5f7fa"/>`
      
      // 添加干扰线
      lines.forEach(line => {
        svg += `<line x1="${line.x1}" y1="${line.y1}" x2="${line.x2}" y2="${line.y2}" stroke="${line.stroke}" stroke-width="1"/>`
      })
      
      // 添加干扰点
      dots.forEach(dot => {
        svg += `<circle cx="${dot.cx}" cy="${dot.cy}" r="${dot.r}" fill="${dot.fill}"/>`
      })
      
      // 添加验证码文字
      for (let i = 0; i < code.length; i++) {
        const char = code[i]
        const x = 25 + i * 20
        const y = 25 + (Math.random() - 0.5) * 10
        const rotation = (Math.random() - 0.5) * 30
        const fontSize = 20 + Math.random() * 5
        const color = `rgb(${50 + Math.floor(Math.random() * 100)}, ${50 + Math.floor(Math.random() * 100)}, ${50 + Math.floor(Math.random() * 100)})`
        
        svg += `<text x="${x}" y="${y}" font-size="${fontSize}" fill="${color}" text-anchor="middle" font-weight="bold" transform="rotate(${rotation}, ${x}, ${y})">${char}</text>`
      }
      
      svg += `</svg>`
      
      // 转换为base64
      const base64 = btoa(unescape(encodeURIComponent(svg)))
      return `data:image/svg+xml;base64,${base64}`
    },
    
    getCode() {
      try {
        // 强制启用验证码
        this.captchaEnabled = true
        // 使用本地生成的验证码
        this.codeUrl = this.createSvgCaptcha()
        this.loginForm.uuid = 'local-captcha' // 设置一个固定的uuid
        console.log('验证码已生成:', this.currentCode)
      } catch (error) {
        console.error('生成验证码失败:', error)
        // 显示错误占位图片
        this.codeUrl = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='40' viewBox='0 0 120 40'%3E%3Crect width='120' height='40' fill='%23f5f7fa' stroke='%23dcdfe6'/%3E%3Ctext x='60' y='25' text-anchor='middle' fill='%23f56c6c' font-size='14'%3E验证码生成失败%3C/text%3E%3C/svg%3E"
      }
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 验证码本地验证
          if (this.loginForm.uuid === 'local-captcha') {
            if (this.loginForm.code.toLowerCase() !== this.currentCode.toLowerCase()) {
              this.$message.error('验证码错误')
              this.getCode()
              return
            }
          }
          
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 })
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove('rememberMe')
          }
          
          // 尝试登录
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{})
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  font-family: 'Helvetica Neue', Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 背景装饰元素 */
.background-decorations {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

.decoration-wave {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  background: linear-gradient(90deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
  clip-path: polygon(0 100%, 100% 0, 100% 100%, 0 100%);
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

/* 登录容器 */
.login-container {
  position: relative;
  z-index: 10;
  width: 100%;
  max-width: 480px;
  margin: 0 20px;
}

/* 品牌区域 */
.brand-section {
  text-align: center;
  margin-bottom: 40px;
  color: white;
}

.brand-logo {
  margin-bottom: 20px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  color: white;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

.system-title {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 12px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  letter-spacing: 1px;
}

.system-description {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
  font-weight: 300;
}

/* 登录表单 */
.login-form {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.form-title {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 30px 0;
  position: relative;
}

.form-title::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 2px;
}

/* 表单元素样式 */
.el-form-item {
  margin-bottom: 24px;
}

.el-input {
  .el-input__inner {
    border-radius: 8px;
    border: 1px solid #e1e8ed;
    transition: all 0.3s ease;
    font-size: 14px;
    
    &:focus {
      border-color: #667eea;
      box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
    }
  }
  
  .el-input__prefix {
    color: #667eea;
  }
}

/* 验证码容器 */
.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.login-code {
  flex-shrink: 0;
  width: 120px;
  height: 40px;
  
  .login-code-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
    cursor: pointer;
    border: 1px solid #e1e8ed;
    transition: transform 0.2s ease;
    background-color: #f5f7fa;
    
    &:hover {
      transform: scale(1.02);
      border-color: #667eea;
    }
  }
}

/* 响应式验证码样式 */
@media (max-width: 480px) {
  .captcha-container {
    flex-direction: column;
    gap: 12px;
  }
  
  .login-code {
    width: 100%;
    height: 44px;
  }
}

/* 表单选项 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .el-checkbox {
    color: #666;
  }
  
  .forgot-password {
    color: #667eea;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.3s ease;
    
    &:hover {
      color: #764ba2;
      text-decoration: underline;
    }
  }
}

/* 登录按钮 */
.login-button {
  width: 100%;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-size: 16px;
  font-weight: 500;
  height: 48px;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
  }
  
  &:active {
    transform: translateY(0);
  }
}

/* 特色功能区域 */
.feature-section {
  display: flex;
  justify-content: space-around;
  margin-top: 30px;
  padding-top: 30px;
  border-top: 1px solid #f0f0f0;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  color: #666;
  font-size: 12px;
  
  .feature-icon {
    font-size: 20px;
    color: #667eea;
    margin-bottom: 8px;
  }
  
  span {
    line-height: 1.4;
  }
}

/* 底部信息 */
.login-footer {
  position: absolute;
  bottom: 20px;
  left: 0;
  width: 100%;
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  z-index: 5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    margin: 0 16px;
  }
  
  .login-form {
    padding: 30px 24px;
  }
  
  .system-title {
    font-size: 24px;
  }
  
  .system-description {
    font-size: 14px;
  }
  
  .feature-section {
    flex-direction: column;
    gap: 16px;
  }
  
  .feature-item {
    flex-direction: row;
    justify-content: flex-start;
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .login-form {
    padding: 24px 20px;
  }
  
  .brand-logo {
    margin-bottom: 16px;
  }
  
  .logo-icon {
    width: 60px;
    height: 60px;
  }
  
  .system-title {
    font-size: 20px;
  }
  
  .captcha-container {
    flex-direction: column;
    gap: 12px;
  }
  
  .login-code {
    width: 100%;
    text-align: center;
  }
}
</style>
